// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    searchValue: '',
    //是否开启了蓝牙
    isBluetooth: true,
    deviceList: [],
    // 过滤设备名称白名单
    filterDeviceList: [
      'JDY-',
      'BT-',
      '李玉祥',
    ],
    searchTypeOption: [
      { text: '设备编码', value: 0 },
      { text: '设备名称', value: 1 }
    ],
    searchTypeValue: 0,
  },
  // 事件处理函数
  bindViewTap() {
  },
  onLoad() {
    console.log(app.globalData.loginUser)
    if (!app.globalData.loginUser) {
      return;
    }
    this.initBluetooth()
    //获取用户授权设置
    // this.getSetting();
    //初始化蓝牙适配器
    // this.openBluetoothAdapter();
    //开启蓝牙搜索
    // this.startBluetoothDevicesDiscovery();

  },
  //界面显示
  onShow() {
    console.log(app.globalData.loginUser)
    if (!app.globalData.loginUser) {
      return;
    }
    if (!this.data.deviceList) {
      this.initBluetooth()
    }
  },
  initBluetooth() {
    var that = this
    wx.openBluetoothAdapter({
      success: function (res) {
        that.findBlue()
        that.setData({
          isBluetooth: true
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '请打开手机蓝牙！',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },


  findBlue() {
    var that = this
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      success: function (res) {
        that.getBlue()
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },

  getBlue() {
    var that = this
    var searchResult = false
    var index = 0

    wx.showLoading({
      title: '搜索设备...',
    })
    //定时搜索
    // setInterval(function () {

    // wx.getBluetoothDevices({
    //   success: function (res) {
    //     console.log(res)
    //     that.setData({
    //       deviceList: res.devices
    //     })
    //   },
    //   fail: function (res) {
    //     console.log(res)
    //   }
    //   //   },500)
    // })
    // wx.getBluetoothDevices({
    //   success: function (res) {
    //     console.log(res)
    //     //根据设备名称匹配   这里的meterId是需要匹配的设备名称，可以过滤掉不需要的设备
    //     var meterId = ""
    //     // for (var i = 0; i < res.devices.length; i++) {
    //     //   if ((res.devices[i].name + "").substr(0, 16) == meterId || (res.devices[i].localName + "").substr(0, 16) == meterId) {
    //     //     that.setData({
    //     //       deviceList: res.devices
    //     //     })
    //     //   }
    //     // }
    //     that.setData({
    //       deviceList: res.devices
    //     })
    //     wx.hideLoading()
    //   }
    // })




    //定时搜索
    var interval = setInterval(function () {
      wx.getBluetoothDevices({
        success: function (res) {
          console.log(res)
          index = index + 1
          console.log(index)
          if (!searchResult) {
            for (var i = 0; i < res.devices.length; i++) {
              that.setData({
                deviceList: that.filterDevice(res.devices)
              })
              if (res.devices.length > 0) {
                clearInterval(interval)
              }
              wx.hideLoading()
              return
            }
          }
        }
      })
    }, 2000)

  },
  refreshBtn() {
    if (this.data.searchValue != '' || this.data.searchValue != null || this.data.searchValue != undefined) {
      wx.showLoading({
        title: '搜索设备...',
      })
      let searchTypeValue = this.data.searchTypeValue
      if (searchTypeValue == 0) {
        this.searchByDeviceId()
      } else {
        this.searchByDeviceName()
      }
    } else {
      this.getBlue()
    }
  },
  connetBlue(e) {
    let deviceInfo = e.currentTarget.dataset.currentdevice
    //判断是否可以连接
    if (!deviceInfo.connectable) {
      wx.showToast({
        title: '该设备不可连接！',
        icon: 'none',
        duration: 2000
      })
      return
    }
    let deviceId = deviceInfo.deviceId
    var that = this
    that.setData({
      deviceId
    })
    wx.hideLoading()
    wx.showLoading({
      title: '连接设备...',
    })
    wx.createBLEConnection({
      deviceId: deviceId,
      success: function (res) {
        wx.showToast({
          title: '连接设备成功！',
          icon: 'none',
          image: '',
          duration: 1500,
          mask: false
        });
        wx.stopBluetoothDevicesDiscovery() //关闭蓝牙搜索
        //TODO 跳转阀门详情页面
        wx.navigateTo({
          url: '../valveInformation/index?deviceId=' + deviceId,
        })
        // that.getServiceId() //获取服务ID
      },
      fail: function (res) {
        console.log(res)
        wx.hideLoading()
        wx.showToast({
          title: '连接设备失败：' + res.errMsg,
          icon: 'none',
          duration: 2000
        })
        wx.stopBluetoothDevicesDiscovery() //关闭蓝牙搜索
      }
    })
  },





























  //初始化蓝牙适配器
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log(res)
      },
      fail: (res) => {
        console.log(res)
      },
      complete: (res) => {
        console.log(res)
      }
    })
  },
  //开启蓝牙搜索
  startBluetoothDevicesDiscovery() {
    wx.startBluetoothDevicesDiscovery({
      success: (res) => {
        console.log(res)
      },
      fail: (res) => {
        console.log(res)
      }
    })
  },
  //获取蓝牙设备列表
  getBluetoothDevices() {
    wx.getBluetoothDevices({
      success: (res) => {
        console.log(res)
      },
      fail: (res) => {
        console.log(res)
      }
    })
  },
  //监听寻找到新设备的事件
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      console.log(res)
    })
  },
  //停止搜寻附近的蓝牙外围设备
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery({
      success: (res) => {
        console.log(res)
      },
      fail: (res) => {
        console.log(res)
      }
    })
  },
  //获取用户授权设置
  getSetting() {
    wx.getSetting({
      success: (res) => {
        //获取用户authSetting下的scope.bluetooth值
        //如果bluetoothFlag为true，说明用户已经授权，可以直接调用蓝牙接口，否则需要调用wx.authorize()方法，让用户授权
        if (res.authSetting['scope.bluetooth']) {
          console.log('用户已授权')
        } else {
          wx.authorize({
            scope: 'scope.bluetooth',
            success() {
              console.log('用户已授权')
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              // wx.startRecord()
              wx.openBluetoothAdapter()
            },
            fail() {
              console.log('用户未授权');
              wx.showToast({
                title: '请在右上角设置中开启蓝牙功能',
                icon: 'none',
                image: '',
                duration: 1500,
                mask: false,
                success: (result) => {
                  console.log('请在右上角设置中开启蓝牙功能')
                  wx.openSetting({
                    success: (result) => {
                      if (result.authSetting['scope.bluetooth']) {
                        // 用户已经同意小程序使用蓝牙功能，后续调用 wx.startBluetoothDevicesDiscovery 接口不会弹窗询问
                        wx.openBluetoothAdapter()

                      }
                    },
                    fail: () => { },
                    complete: () => { }
                  });
                },
                fail: () => { },
                complete: () => { }
              });
            }
          })
        }
        console.log(res)
      }, fail: (res) => {
        console.log(res)
      }
    })
  },
  //搜索蓝牙设备
  onSearch(e) {
    wx.showLoading({
      title: '搜索设备...',
    })
    let detail = e.detail
    if (detail == '' || detail == undefined) {
      this.findBlue()
      return
    }
    let that = this
    let searchTypeValue = that.data.searchTypeValue
    if (searchTypeValue == 0) {
      that.searchByDeviceId()
    } else {
      that.searchByDeviceName()
    }
  },
  //按设备id搜索蓝牙
  searchByDeviceId() {
    let that = this
    let deviceId = that.data.searchValue
    let deviceList = []
    wx.getBluetoothDevices({
      success: (res) => {
        console.log(res)
        let filterDeviceList = this.filterDevice(res.devices)
        filterDeviceList.forEach((item, index) => {
          //模糊匹配
          if (item.deviceId.indexOf(deviceId) >= 0) {
            deviceList.push(item)
          }
        })
        that.setData({
          deviceList
        })
        wx.hideLoading()
      }
    })
  },
  //按设备名称搜索蓝牙
  searchByDeviceName() {
    let that = this
    let deviceName = that.data.searchValue
    let deviceList = []
    wx.getBluetoothDevices({
      success: (res) => {
        console.log(res)
        let filterDeviceList = this.filterDevice(res.devices)
        filterDeviceList.forEach((item, index) => {
          //模糊匹配
          if (item.name.indexOf(deviceName) >= 0) {
            deviceList.push(item)
          }
        })
        that.setData({
          deviceList
        })
        wx.hideLoading()
      }
    })
  },
  //过滤蓝牙设备，只显示deviceFilter里面xx-开头的设备
  filterDevice(list) {
    let temp = []
    console.log(list)
    list.filter((item, index) => {
      //过滤item.name从this.data.deviceFilterList中存在的设备
      this.data.filterDeviceList.forEach(item1 => {
        if (item.name.indexOf(item1) >= 0) {
          temp.push(item)
        }
      });
    })
    return temp;
  }
})
